import api from './appOnLaunch.js';
import store from '../store/index.js'
import event from './event.js';
import $const from './const.js';
import Vue from 'vue';

let userinfo = null;

export default {
	getuserinfoResolve: null,
	getuserinfoReject: null,

	getInfo(id = 0) {
		if (id == 0) {
			let Info = Vue.prototype.$storage.getStorageSync('userinfo');
			Vue.prototype.$t.vuex('userinfo', Info)
		}
		return new Promise((resolve, reject) => {
			let userid = id;
			if (userid == 0) {
				userid = Vue.prototype.$storage.getStorageSync('userid');
			}
			Vue.prototype.$request({
				url: api.user.getinfo,
				method: "POST",
				data: {
					userId: userid
				}
			}).then(response => {
				let {
					UserRights
				} = response;
				Vue.prototype.$t.vuex('userinfo', response)

				return resolve(userinfo);
			}).catch(e => {
				return reject(e);
			});
		});
	},
	/**
	 * 
	 * 根据页面ID获取该页面的权限
	 */
	getAuth(FItemId) {
		if (!FItemId) return false;
		let userinfo = Vue.prototype.$storage.getStorageSync('userinfo');
		//获取到页面的类型
		let menu = ROUTES;
		var pages = getCurrentPages();
		var route2 = pages[pages.length - 1];
		let UserRights = userinfo && userinfo.UserRights && userinfo.UserRights.UserRights

		if (UserRights.length < 1) {
			return false;
		}
		UserRights = UserRights.find(rule => rule.FItemId == FItemId);

		menu = menu.find(rule => {
			
			if (route2) {
				return rule.path.slice(1) == route2.route && rule.meta.FItemId == FItemId
			}
			return rule.meta.FItemId == FItemId
		});
		// console.log('2UserRights', UserRights)
		if (!UserRights) {
			return false;
		}
		return {
			...UserRights,
			...menu
		}
	},
	isLogin() {
		let accessToken = Vue.prototype.$storage.getStorageSync('accessToken');
		if (accessToken) {
			// console.log('accessToken', accessToken)
			return true;
		} else {
			return false;
		}
	},
	loginout() {
		// console.log('loginout 1s')

		setTimeout(() => {
			uni.redirectTo({
				url: 'discoveryPages/login',
			})
		}, 500)

		uni.clearStorageSync() //刷新storage的数据
	},
}